import React from "react";
import ReactDOM from "react-dom";
import { connect } from "dva";
import {
  Button,
  Icon,
  Radio,
  Form,
  Input,
  message,
  Upload,
  Progress
} from "antd";
import "./Article.scss";
import "dashjs";
import Ueditor from "./Ueditor";
import { UrlConfig } from "../../../services/fetch";
import { uploadImgBase64, getConfig } from "../../../services/fetch";
import { noImg } from "../../../utils/request";
import { Transform } from "stream";
// import { guid } from '../../../utils/Date';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { TextArea } = Input;

@connect(({ add }) => ({
  add: add
}))
class Article extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      editorHtml: "",
      editorText: "",
      radioValue: 1,
      marginLeft: 0,
      marginRight: 0,
      titleLength: 0,
      keyLength: 0,
      introLength: 0,
      progress: 0
    };
    this.props.onRef(this);
  }

  componentDidMount() {
    // window.PubSub.subscribe('editor', this.setEditor)
    window.PubSub.subscribe("pushDataToContent", this.pushDataToContent);
  }

  pushDataToContent = item => {
    this.props.form.setFieldsValue(item);
  };
  //从内容库选择到编辑器
  setUeditor = () => {
    let ue = window.UE.getEditor("content");
    ue.focus();
    this.props.dispatch({ type: "add/saveMchType", data: "editor" });
  };
  showVideoModal = e => {
    // console.log(e)
  };
  //订阅
  setEditor = data => {
    let ue = window.UE.getEditor("content");
    //设置文本值
    let datas = "";

    //如果当前标题为空，那么则使用内容库的素材标题
    let formData = this.props.form.getFieldsValue();
    if (!formData.information_title) {
      this.props.form.setFieldsValue({
        information_title: data.name
      });
    }
    // console.log(data);

    switch (data.type) {
      case "biz_sobey_picture":
        if (data.streamingUrl == "") {
          message.error("当前素材不可用");
          return;
        }
        datas = `<img src="${data.streamingUrl}" alt='...'/>`;
        break;
      case "biz_sobey_video":
        if (data.streamingUrl == "") {
          message.error("当前素材不可用");
          return;
        }
        datas = `<p style="text-align:center"><video data-dashjs-player id="${data.contentId}" src="${data.streamingUrl}" poster="${data.keyFrameUrl}"
                controls webkit-playsinline="true" x-webkit-airplay="true"
                playsinline="true" x5-playsinline="true"></video></p><h3 style="display: none"><br /> ${data.name}</h3>`;
        break;
      case "biz_sobey_audio":
        if (data.streamingUrl == "") {
          message.error("当前素材不可用");
          return;
        }
        datas = `<p><audio src=${data.streamingUrl} style="margin: 10px auto;display: block;" controls>您的浏览器不支持 audio 标签。</audio></p>`;
        break;
      case "biz_sobey_hypermedia":
        datas = data.note = data.note.replace(/[\\]/g, "");
        break;
      default:
        break;
    }
    ue.ready(function() {
      ue.execCommand("insertHtml", datas);

      // ue.setContent('<p>　</p>', true);
      // window.dashjs.MediaPlayerFactory.createAll();
      // window.player = window.dashjs.MediaPlayer().create();
      // window.player.initialize(document.querySelector("#"+data.contentId), data.streamingUrl, true);
    });
  };
  onChangeRadio = e => {
    this.setState({
      radioValue: e.target.value
    });
    if (e.target.value == 1) {
      this.setFields({
        url: ""
      });
    }
  };
  /**
   * 关闭
   */
  close = key => {
    this.props.dispatch({
      type: "add/close",
      key: key
    });
  };
  /**
   * 推荐左滑按钮
   */
  left = () => {
    let marginLeft = this.state.marginLeft + 145;
    if (marginLeft >= 0) {
      this.setState({
        marginLeft: 0
      });
    } else {
      this.setState({
        marginLeft: marginLeft
      });
    }
  };

  /**
   * 推荐右滑按钮
   */
  right = () => {
    let marginLeft = this.state.marginLeft - 145;
    let length = (this.props.add.gltjData.length - 4) * 145;
    if (marginLeft <= -length) {
      this.setState({
        marginLeft: -length
      });
    } else {
      this.setState({
        marginLeft: marginLeft
      });
    }
  };

  /**
   * 获取表单的值
   */
  getFieldsValueTab = () => {
    let data = this.props.form.getFieldsValue();
    let about = [];
    this.props.add.gltjData.map((item, index) => {
      about.push(item.information_id);
    });
    data["about"] = about.join();
    data["type"] = 1;
    let ue = window.UE.getEditor("content");
    data.content = ue.getContent();

    return data;
  };

  /**
   * 获取表单值
   */
  getFieldsValue = () => {
    let data = this.props.form.getFieldsValue();

    this.props.form.validateFields();
    let intro = document.getElementById("introInput").innerText;
    console.log(intro);
    data.intro = intro;
    let validateArr = this.props.form.getFieldsError();
    let isDown = true;
    for (const key in validateArr) {
      if (validateArr.hasOwnProperty(key)) {
        //判断是否有效验错误
        if (validateArr[key]) {
          isDown = false;
          return;
        }
      }
    }
    if (isDown) {
      let about = [];
      this.props.add.gltjData.map((item, index) => {
        about.push(item.information_id);
      });
      data["about"] = about.join();
      data["type"] = 1;
      let ue = window.UE.getEditor("content");
      data.content = ue.getContent();

      return data;
    }
  };
  /**
   * 重置表单
   */
  resetFields = () => {
    this.props.form.resetFields();
    let ue = window.UE.getEditor("content");
    ue.execCommand("cleardoc");
  };
  /**
   * 设置值
   */
  setFields = data => {
    let formData = this.props.form.getFieldsValue();
    // if (formData.information_title) {
    //     data.information_title = formData.information_title;
    // }

    this.props.form.setFieldsValue(data);
    document.getElementById("introInput").innerText=data.intro
    //如果是URL链接
    if (data.url) {
      this.setState({
        radioValue: 2
      });
    } else {
      this.setState({
        radioValue: 1
      });
    }

    //只有在使用已发布视频或资讯时才会执行此处
    if (data.mType) {
      if (data.mType == "video") {
        if (data.video_type == 1) {
          let ue = window.UE.getEditor("content");
          ue.focus();
          let datas = `<p></p><p></p><video src="${data.video_src}"  poster="${data.thumbnail}"
                                controls
                                webkit-playsinline="true"
                                x-webkit-airplay="true"
                                playsinline="true"
                                x5-playsinline="true"
                               >
                                您的浏览器不支持 video 标签。
                                </video><p></p>`;
          ue.execCommand("insertHtml", datas);
        } else if (data.video_type == 2) {
          this.createAudioToUeditor(data.video_src);
        }
      } else if (data.mType == "information") {
        let ue = window.UE.getEditor("content");
        ue.focus();
        ue.execCommand("insertHtml", data.content);
      }
    }
    //此处操作编辑器内容移动到编辑器组件内部操作
    // if (data.content) {
    //     window.onload = function () {
    //         let ue = window.UE.getEditor('content');
    //         ue.ready(function () {
    //             ue.setContent(data.content);
    //         });
    //     }
    //     // setTimeout(() => { //有时UE 还没加载完成，后端数据就返回了，会报错
    //     //     let ue = window.UE.getEditor('content');
    //     //     ue.ready(function () {
    //     //         ue.setContent(data.content);
    //     //     });
    //     // }, 1000)

    // }
    if (data.about) {
      this.props.dispatch({ type: "add/setPushClick", data: data.about_list });
    }
  };
  /**
   * 获取title length
   */
  getTitleLength = e => {
    let length = e.target.value.length;
    if (length <= 250) {
      this.setState({
        titleLength: length
      });
    }
    window.PubSub.publish("tabTitle", e.target.value);
  };

  /**
   * 创建音频到富文本中
   */
  createAudioToUeditor = url => {
    let ue = window.UE.getEditor("content");
    ue.focus();
    let datas = `<p></p><audio style="margin: 10px auto;display: block;" src="${url}" controls>您的浏览器不支持 audio 标签。</audio><p></p>`;
    ue.execCommand("insertHtml", datas);
  };

  /**
   * 创建图片到富文本中
   */
  createImgToUeditor = url => {
    let ue = window.UE.getEditor("content");
    ue.focus();
    let datas = `<p></p><img style="margin: 10px auto;display: block;" src="${url}" /><p></p>`;
    ue.execCommand("insertHtml", datas);
  };

  /**
   * 创建视频到富文本中
   */
  createVideoToUeditor = url => {
    /**
     * 上传视频自动生成封面图功能  详解
     * 调用上传视频接口后端返回上传成功mp4地址，先放到一个隐藏的video标签中，然后利用canvas的drawImage方法截取视频关键帧，获得图片的base64地址
     * 然后在调用后端接口将base64地址上传后转换成.jpg的资源文件地址，最后在设置到video标签的poster属性上，完成视频上传自动生成封面图功能
     *
     * 彩蛋，crossorigin="anonymous" 加了这个属性后可解决canvas获取跨域资源问题
     * 但是需要后端配合修改Access-Control-Allow-Origin
     * 由于本地老是报错出现跨域问题，至今没解决。所以每次只有佛系修改代码。打包后传到服务器上测试。
     *
     * */
    let canvas = document.createElement("canvas");
    let hidden_video = document.getElementById("hidden_video");
    let data;
    var timeStamp = +new Date();
    hidden_video.setAttribute("src", url + "?" + timeStamp);
    const hide = message.loading("视频上传成功,封面图生成中...", 0);

    hidden_video.oncanplay = () => {
      var videoWidth =
        hidden_video.videoWidth > 0 ? hidden_video.videoWidth : 295;
      var videoHeight =
        hidden_video.videoHeight > 0 ? hidden_video.videoHeight : 165;
      var width = videoWidth > 640 ? 640 : videoWidth;

      var height = videoHeight * (width / videoWidth);

      // console.log(hidden_video);
      canvas.width = width; //这个设置不能丢，否者会成为canvas默认的300*150的大小
      canvas.height = height; //这个设置不能丢，否者会成为canvas默认的300*150的大小
      let ctx = canvas.getContext("2d"); //创建画布
      // hidden_video.setAttribute('crossOrigin', 'anonymous');

      ctx.drawImage(hidden_video, 0, 0, width, height); //将视频写入canvas

      data = canvas.toDataURL("images/png"); //
      // console.log(data);

      uploadImgBase64({ img: data }).then(res => {
        // console.log(res);
        if (res.data.code == 200) {
          setTimeout(hide, 100);
          let ue = window.UE.getEditor("content");
          ue.focus();
          let datas = `<p></p><p></p><video  src="${url}"  poster="${res.data.data}"
                                controls
                                webkit-playsinline="true"
                                x-webkit-airplay="true"
                                playsinline="true"
                                x5-playsinline="true"
                               >
                                您的浏览器不支持 video 标签。
                                </video><p></p>`;

          ue.execCommand("insertHtml", datas);
        }
      });
    };
  };

  /**
   * 上传文件插件
   */
  fcUpload = type => {
    // let max_size = 2000;
    // if (type == 'audio') {
    //     max_size = 20;
    // }
    // let multiple = true;
    // if(type == 'video' || type == 'audio'){
    //     multiple = false
    // }
    // window.fc = new window.FcUpload({
    //     elem: 'fcUpload' + type,
    //     oss: this.props.add.configJson.aliyunOssSwitch,       //是否为oss 上传
    //     multiple: multiple,  //是否允许上传多个文件
    //     type: type, // 上传文件类型\ img 图片，  video 视频
    //     actionImg: `${UrlConfig}/fcpublic/uploads/uploadImg`,  //本地上传图片地址
    //     actionVideo: `${UrlConfig}/fcpublic/uploads/uploadVideo`,  //本地上传视频地址
    //     actionOss: this.props.add.configJson.actionOss,  //后端认证接口，获取临时上传凭证
    //     endpoint: this.props.add.configJson.endpoint,
    //     bucket: this.props.add.configJson.bucket,
    //     customDomain: this.props.add.configJson.customDomain,
    //     ossConfig: this.props.add.configJson,
    //     maxSize: max_size,
    //     callback: (callRes) => {
    //         console.log(callRes);
    //         let url;
    //         if(callRes.newResponse.length > 1 && type == 'video'){
    //             message.error('视频暂不支持批量上传');
    //             return ;
    //         }
    //         callRes.newResponse.forEach(async (url) => {
    //             if (!url) {
    //                 return;
    //             }
    //             switch (type) {
    //                 case 'video':
    //                     await this.createVideoToUeditor(url);
    //                     break;
    //                 case 'audio':
    //                     this.createAudioToUeditor(url);
    //                     break;
    //                 case 'img':
    //                     this.createImgToUeditor(url);
    //                     break;
    //             }
    //         })
    //     }
    // });
    // window.fc.show();
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    // 正则验证url地址是否正确
    const myValidateFields = (rule, values, callback) => {
      var reg = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/;
      if (values) {
        if (!reg.test(values)) {
          callback("请输入正确的URL");
        }
      }
      callback();
    };
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      }
    };
    const _that = this;
    // const props = {
    //     name: 'video',
    //     showUploadList: false,
    //     action: UrlConfig + '/fcinformation/Information/uploadVideo',
    //     headers: {
    //         authorization: 'authorization-text',
    //     },
    //     onChange(info) {
    //         if (info.file.status === 'uploading') {
    //             // console.log(info.file, info.fileList);
    //             _that.setState({
    //                 progress: info.file.percent
    //             })
    //         }
    //         if (info.file.status === 'done' && info.file.response.code === 200) {

    //             /**
    //              * 上传视频自动生成封面图功能  详解
    //              * 调用上传视频接口后端返回上传成功mp4地址，先放到一个隐藏的video标签中，然后利用canvas的drawImage方法截取视频关键帧，获得图片的base64地址
    //              * 然后在调用后端接口将base64地址上传后转换成.jpg的资源文件地址，最后在设置到video标签的poster属性上，完成视频上传自动生成封面图功能
    //              *
    //              * 彩蛋，crossorigin="anonymous" 加了这个属性后可解决canvas获取跨域资源问题
    //              * 但是需要后端配合修改Access-Control-Allow-Origin
    //              * 由于本地老是报错出现跨域问题，至今没解决。所以每次只有佛系修改代码。打包后传到服务器上测试。
    //              *
    //              * */
    //             let canvas = document.createElement("canvas");
    //             let hidden_video = document.getElementById('hidden_video');
    //             let data;
    //             var timeStamp = + new Date();
    //             hidden_video.setAttribute('src', info.file.response.data.video_path + '?' + timeStamp);
    //             const hide = message.loading('视频上传成功,封面图生成中...', 0);

    //             hidden_video.oncanplay = () => {
    //                 // console.log(hidden_video);
    //                 canvas.width = 649;//这个设置不能丢，否者会成为canvas默认的300*150的大小
    //                 canvas.height = 360;//这个设置不能丢，否者会成为canvas默认的300*150的大小
    //                 let ctx = canvas.getContext('2d'); //创建画布
    //                 // hidden_video.setAttribute('crossOrigin', 'anonymous');

    //                 ctx.drawImage(hidden_video, 0, 0, 649, 360); //将视频写入canvas

    //                 data = canvas.toDataURL('images/png'); //
    //                 // console.log(data);

    //                 uploadImgBase64({ img: data }).then((res) => {
    //                     // console.log(res);
    //                     if (res.data.code == 200) {
    //                         setTimeout(hide, 100);
    //                         let ue = window.UE.getEditor('content');
    //                         ue.focus();
    //                         let datas = `<p></p><p></p><video  src="${info.file.response.data.video_path}"  poster="${res.data.data}" controls>您的浏览器不支持 video 标签。</video><p></p>`

    //                         ue.execCommand('insertHtml', datas);
    //                     }
    //                 })
    //             }
    //         } else if (info.file.status === 'error') {
    //             message.error(`${info.file.name} 上传失败`);
    //             this.setState({
    //                 progress: 0
    //             })
    //         }
    //     },
    // };
    let gltjData = this.props.add.gltjData;
    if (!gltjData) {
      gltjData = [];
    }

    //解决Tabs切换时，Footer组件点击保存Acticle组件this无法传递到父Add组件
    this.props.onRef(this);
    const formValues = this.props.form.getFieldsValue();

    return (
      <div
        className="Article1"
        style={this.state.radioValue === 2 ? { top: 15, left: -480, width: 900, height: 900} : {}}
      >
        <Form>
          <FormItem label="">
            {getFieldDecorator("url", {
              rules: [
                {
                  required: false,
                  validator: myValidateFields
                }
              ]
            })(
              <Input
                placeholder="URL ᠴᠥᠷᠬᠡᠯᠡᠭᠡ ᠣᠷᠣᠭᠤᠯᠤᠭᠠᠷᠠᠶ"
                style={this.state.radioValue === 1 ? { display: "none" } : {}}
              />
            )}
          </FormItem>
          <div
            style={this.state.radioValue === 2 ? { display: "none" } : {}}
            className="editor_box"
          >
            <Ueditor
              id="content"
              title={formValues.information_title}
              configJson={this.props.add.configJson}
              match={this.props.match}
            />
          </div>
          <Progress
            style={
              this.state.progress === 0 || this.state.progress === 100
                ? { display: "none" }
                : {}
            }
            percent={this.state.progress}
            status="active"
            showInfo={false}
          />
          {this.props.add.configJson.mchSwitch ? (
            <Button
              style={this.state.radioValue === 2 ? { display: "none" } : {}}
              onClick={this.setUeditor}
            >
              {/* 从内容库选择 */}
              ᠠᠭᠤᠯᠭ᠎ᠠ ᠶ᠋ᠢᠨ ᠬᠥᠮᠦᠷᠭᠡ ᠡᠴᠡ ᠰᠣᠩᠭᠤᠬᠤ
            </Button>
          ) : (
            ""
          )}
          {/* 内容编辑模式、URL模式 */}
          <RadioGroup
            className="radioGroup-box"
            onChange={this.onChangeRadio}
            value={this.state.radioValue}
            style={{ marginBottom: "20px" }}
          >
            <Radio value={1}>ᠨᠠᠢᠷᠠᠭᠤᠯᠬᠤ ᠬᠡᠪ</Radio>
            <Radio value={2}>URL ᠬᠡᠪ</Radio>
          </RadioGroup>
          {/* 摘要 */}
          <FormItem
            {...formItemLayout}
            label="ᠲᠣᠪᠴᠢᠯᠠᠯ"
            className="introInput_container"
          >
            <p
              id="introInput"
              contenteditable="true"
              className="introInput"
            ></p>
          </FormItem>
          {/* 关键字 */}
          <FormItem
            {...formItemLayout}
            label="ᠵᠠᠩᠭᠢᠯᠠᠭ᠎ᠠ ᠶ᠋ᠢᠨ ᠦᠭᠡ"
            className="keyInput_container"
          >
            {getFieldDecorator("key_words")(
              <Input
                className="keyInput"
                onChange={e => {
                  let data = e.target.value;
                  if (data.length <= 250) {
                    this.setState({
                      keyLength: data.length
                    });
                  }
                }}
                maxLength={250}
              />
            )}
            <span className="showKeyLength">{this.state.keyLength}/250</span>
          </FormItem>
          {/* 标题 */}
          <FormItem label="">
            <p className="title_show">
              <span className="required" style={{ color: "red" }}>
                *
              </span>
              {getFieldDecorator("information_title", {
                rules: [
                  {
                    required: true,
                    message: "ᠭᠠᠷᠴᠠᠭ ᠢ᠋ᠶ᠋ᠠᠨ ᠣᠷᠤᠭᠤᠯᠤᠭᠠᠷᠠᠢ"
                  }
                ]
              })(
                <Input
                  placeholder="ᠭᠠᠷᠴᠠᠭ ᠢ᠋ᠶ᠋ᠠᠨ  ᠤᠷᠤᠭᠤᠯ                  "
                  className="artical_title"
                  onChange={this.getTitleLength}
                  size="large"
                  style={{ width: "100%", paddingRight: "90px" }}
                  maxLength={250}
                />
              )}
              <span className="rightInput">{this.state.titleLength}/250</span>
            </p>
          </FormItem>
        </Form>
      </div>
    );
  }
}

const ArticleForm = Form.create()(Article);
export default ArticleForm;
